package com.zb777.shuzhilingxi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zb777.shuzhilingxi.Pojo.entity.ChatHistoryDetail;
import com.zb777.shuzhilingxi.Pojo.entity.ChatHistoryList;
import com.zb777.shuzhilingxi.context.BaseContext;
import com.zb777.shuzhilingxi.mapper.ChatHistoryDetailMapper;
import com.zb777.shuzhilingxi.mapper.ChatHistoryListMapper;
import com.zb777.shuzhilingxi.result.Result;
import com.zb777.shuzhilingxi.service.IChatHistoryListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author redaiyu
 * @since 2025-07-13
 */
@Service
public class ChatHistoryListServiceImpl extends ServiceImpl<ChatHistoryListMapper, ChatHistoryList> implements IChatHistoryListService {
    @Autowired
    private ChatHistoryDetailMapper detailMapper;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 创建聊天列表（含系统欢迎消息）
     */
    @Override
    @Transactional
    public ChatHistoryList createChatList(ChatHistoryList chatHistoryList) {
        Integer userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 1. 创建聊天列表
        ChatHistoryList chatList = new ChatHistoryList();
        chatList.setName(chatHistoryList.getName() == null ? "新对话" : chatHistoryList.getName());
        chatList.setUserId(userId);
        chatList.setChatCount(1);  // 初始包含系统消息
        chatList.setIsDeleted(false);
        save(chatList);

        // 2. 创建系统欢迎消息
        ChatHistoryDetail welcomeMsg = new ChatHistoryDetail();
        welcomeMsg.setChatHistoryListId(chatList.getChatHistoryListId());
        welcomeMsg.setIsImage(false);
        welcomeMsg.setWords("您好");
        welcomeMsg.setRole("user");
        welcomeMsg.setIsDeleted(false);
        detailMapper.insert(welcomeMsg);

        // 3. 转换为VO返回
        ChatHistoryList vo = new ChatHistoryList();
        BeanUtils.copyProperties(chatList, vo);
        vo.setCreatedAt(chatList.getCreatedAt());
        return vo;
    }

    /**
     * 删除聊天列表（逻辑删除，级联删除详情）
     */
    @Override
    @Transactional
    public void deleteChatList(Integer listId) {
        Integer userId = BaseContext.getCurrentId();
        // 1. 验证列表存在且属于当前用户
        ChatHistoryList chatList = getById(listId);
        if (chatList == null || !chatList.getUserId().equals(userId) || chatList.getIsDeleted()) {
            throw new RuntimeException("聊天列表不存在或无权限删除");
        }

        // 2. 逻辑删除列表
        chatList.setIsDeleted(true);
        updateById(chatList);

        // 3. 逻辑删除该列表下的所有详情
        LambdaUpdateWrapper<ChatHistoryDetail> detailUpdate = new LambdaUpdateWrapper<>();
        detailUpdate.eq(ChatHistoryDetail::getChatHistoryListId, listId)
                .set(ChatHistoryDetail::getIsDeleted, true);
        detailMapper.update(null, detailUpdate);
    }

    /**
     * 编辑聊天列表名称
     */
    @Override
    @Transactional
    public void editChatList(Integer listId, ChatHistoryList dto) {
        Integer userId = BaseContext.getCurrentId();
        // 1. 验证列表存在且属于当前用户
        ChatHistoryList chatList = getById(listId);
        if (chatList == null || !chatList.getUserId().equals(userId) || chatList.getIsDeleted()) {
            throw new RuntimeException("聊天列表不存在或无权限编辑");
        }

        // 2. 更新名称
        chatList.setName(dto.getName());
        updateById(chatList);
    }

    /**
     * 删除聊天详情
     */
    @Override
    @Transactional
    public void deleteChatDetail(Integer detailId) {
        Integer userId = BaseContext.getCurrentId();
        // 1. 验证详情存在
        ChatHistoryDetail detail = detailMapper.selectById(detailId);
        if (detail == null || detail.getIsDeleted()) {
            throw new RuntimeException("聊天记录不存在");
        }

        // 2. 验证所属列表属于当前用户
        Integer listId = detail.getChatHistoryListId();
        ChatHistoryList chatList = getById(listId);
        if (chatList == null || !chatList.getUserId().equals(userId) || chatList.getIsDeleted()) {
            throw new RuntimeException("无权限删除此聊天记录");
        }

        // 3. 逻辑删除详情
        detail.setIsDeleted(true);
        detailMapper.updateById(detail);

        // 4. 更新列表的聊天计数
        if (chatList.getChatCount() > 0) {
            chatList.setChatCount(chatList.getChatCount() - 1);
            updateById(chatList);
        }
    }

    /**
     * 编辑聊天详情（并删除后续消息）
     */
    @Override
    @Transactional
    public ChatHistoryDetail editChatDetail(Integer detailId, ChatHistoryDetail dto) {
        Integer userId = BaseContext.getCurrentId();
        // 1. 验证详情存在
        ChatHistoryDetail detail = detailMapper.selectById(detailId);
        if (detail == null || detail.getIsDeleted()) {
            throw new RuntimeException("消息不存在");
        }

        // 2. 验证所属列表属于当前用户
        Integer listId = dto.getChatHistoryListId();
        ChatHistoryList chatList = getById(listId);
        if (chatList == null || !chatList.getUserId().equals(userId) || chatList.getIsDeleted()) {
            throw new RuntimeException("无权限编辑此消息");
        }

        // 3. 更新消息内容
        detail.setWords(dto.getWords());
        detailMapper.updateById(detail);

        // 4. 删除该消息之后的所有消息
        LambdaUpdateWrapper<ChatHistoryDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ChatHistoryDetail::getChatHistoryListId, listId)
                .gt(ChatHistoryDetail::getChatHistoryDetailId, detailId)  // ID大于当前消息的视为后续消息
                .set(ChatHistoryDetail::getIsDeleted, true);
        detailMapper.update(null, updateWrapper);

        // 5. 重新计算列表的聊天计数
        long activeCount = detailMapper.selectCount(
                new LambdaQueryWrapper<ChatHistoryDetail>()
                        .eq(ChatHistoryDetail::getChatHistoryListId, listId)
                        .eq(ChatHistoryDetail::getIsDeleted, false)
        );
        chatList.setChatCount((int) activeCount);
        updateById(chatList);

        // 6. 转换为VO返回
        ChatHistoryDetail vo = new ChatHistoryDetail();
        BeanUtils.copyProperties(detail, vo);
        vo.setCreatedAt(detail.getCreatedAt());
        return vo;
    }

    /**
     * 获取当前用户的所有聊天列表
     */
    @Override
    public List<ChatHistoryList> getChatLists() {
        Integer userId = BaseContext.getCurrentId();
        List<ChatHistoryList> list = list(
                new LambdaQueryWrapper<ChatHistoryList>()
                        .eq(ChatHistoryList::getUserId, userId)
                        .eq(ChatHistoryList::getIsDeleted, false)
                        .orderByDesc(ChatHistoryList::getCreatedAt)
        );

        // 转换为VO列表
        return list.stream().map(item -> {
            ChatHistoryList vo = new ChatHistoryList();
            BeanUtils.copyProperties(item, vo);
            vo.setCreatedAt(item.getCreatedAt());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取指定列表的聊天详情
     */
    @Override
    public List<ChatHistoryDetail> getChatDetails(Integer listId) {
        Integer userId = BaseContext.getCurrentId();
        // 1. 验证列表属于当前用户
        ChatHistoryList chatList = getById(listId);
        if (chatList == null || !chatList.getUserId().equals(userId) || chatList.getIsDeleted()) {
            throw new RuntimeException("无权限访问此聊天记录或聊天记录不存在");
        }

        // 2. 查询该列表下的所有有效详情
        List<ChatHistoryDetail> details = detailMapper.selectList(
                new LambdaQueryWrapper<ChatHistoryDetail>()
                        .eq(ChatHistoryDetail::getChatHistoryListId, listId)
                        .eq(ChatHistoryDetail::getIsDeleted, false)
                        .orderByAsc(ChatHistoryDetail::getCreatedAt)  // 按时间升序排列
        );

        // 3. 转换为VO列表
        return details.stream().map(item -> {
            ChatHistoryDetail vo = new ChatHistoryDetail();
            BeanUtils.copyProperties(item, vo);
            vo.setCreatedAt(item.getCreatedAt());
            return vo;
        }).collect(Collectors.toList());
    }
}
